import { computed, ref, inject, reactive } from "vue";
import { globalConfig } from "@gd-accbuild-core/config";
import { getBackendDataItems } from "@gd-accbuild-core/config/utils";
const getLoadChildrenMethod = ({
  vmCode,
  pageParams,
  keyField,
  parentKeyField,
  props,
  crudServiceVmTemplateConfig,
}) => {
  const loadChildrenMethod = async ({ row }) => {
    let res = [];
    try {
      res = await globalConfig.getList({
        moduleCode: crudServiceVmTemplateConfig.table.moduleCode,
        vmCode,
        params: {
          [parentKeyField]: row[keyField],
          ...pageParams,
        },
        vmTemplateConfig: crudServiceVmTemplateConfig.table,
      });
      res = getBackendDataItems(res);
    } catch (e) {}
    return Promise.resolve(res);
  };
  return loadChildrenMethod;
};
export const useComputedExpandConfig = (props) => {
  return computed(() => {
    return {
      ...(props.tableCommonAttr?.buildInColumnConfig?.buildInExpand?.config ?? {}),
    };
  });
};

/**
 * 树表相关配置
 */
export const useComputedTreeTableConfig = (props) => {
  ////////////////
  const crudServiceVmTemplateConfig = inject("crudServiceVmTemplateConfig", reactive({ table: {} }));
  //console.log(crudServiceVmTemplateConfig,'crudServiceVmTemplateConfig==============')
  ///////////////
  return computed(() => {
    const vmCode = props.toolBarConfig?.buttons?.find?.((btn) => btn.key === "buildInAddBtn")?.vmCode ?? "";
    const isPaged = props.tableCommonAttr?.paginationConfig?.isPaged ?? false;
    const pageNum = props.tableCommonAttr?.paginationConfig?.pageObj?.pageNum ?? 0;
    const pageSize = props.tableCommonAttr?.paginationConfig?.pageObj?.pageSize ?? 0;
    const keyField =
      props.tableCommonAttr?.treeTableConfig?.keyField ?? props.tableCommonAttr?.rowConfig?.keyField ?? "id";
    const parentKeyField =
      props.tableCommonAttr?.treeTableConfig?.parentKeyField ??
      props.tableCommonAttr?.rowConfig?.parentKeyField ??
      "parentId";
    return {
      transform: props.tableCommonAttr?.treeTableConfig?.transform ?? true,
      rowField: keyField,
      parentField: parentKeyField,
      hasChild: props.tableCommonAttr?.treeTableConfig?.hasChildren ?? "hasChildren",
      lazy: props.tableCommonAttr?.treeTableConfig?.lazy ?? false,
      indent: props.tableCommonAttr?.treeTableConfig?.indent ?? 20,
      expandRowKeys: props.tableCommonAttr?.treeTableConfig?.expandRowKeys ?? [],
      loadMethod:
        props.tableCommonAttr?.treeTableConfig?.loadMethod ??
        getLoadChildrenMethod({
          vmCode,
          pageParams: { isPaged, pageNum, pageSize },
          keyField,
          parentKeyField,
          props,
          crudServiceVmTemplateConfig,
        }),
      //iconOpen: "vxe-icon-square-minus",
      //iconClose: "vxe-icon-square-plus",
      iconOpen: "customize-down-arrow",
      iconClose: "customize-right-arrow",
    };
  });
};

export const useComputedCheckboxConfig = (props) => {
  return computed(() => {
    return {
      ...(props.tableCommonAttr?.buildInColumnConfig?.buildInCheckbox?.config ?? {}),
    };
  });
};

/**
 * 表格编辑配置
 * 三种风格的编辑
 * 1. 行内编辑 且 有按钮需要手动提交
 * "editConfig": {"editableStyle": "Inline", "submitStyle": "Manual", "allowAutoSubmit":true / false}
 * 2. 行内编辑,OnChange / OnBlur时自动提交
 * "editConfig": {"submitStyle": "Auto"//"editableStyle": "Inline",//可有可无,自动只能是Inline}
 * 3. 容器提交
 * "editConfig": {"editableStyle": "Container", "submitStyle": "Manual", "allowAutoSubmit":true / false}
 * 容器编辑 需要配置 Switch 是否允许立即提交,默认非只读禁用的编辑表格为立即提交
 */
export const useComputedEditConfig = (props) => {
  const crudServiceVmTemplateConfig = inject("crudServiceVmTemplateConfig", reactive({ table: {} }));
  return computed(() => {
    const hasEditableConfig = props.tableCommonAttr.hasOwnProperty("editConfig");
    const hasEditableComp = props.tableColMetaList.some((el) => !["Text", "RichText"].includes(el.type));
    if (hasEditableConfig || hasEditableComp) {
      let submitStyle = hasEditableComp ? "Auto" : "Manual";
      if (props.tableCommonAttr.editConfig && props.tableCommonAttr.editConfig.hasOwnProperty("submitStyle")) {
        submitStyle = props.tableCommonAttr.editConfig.submitStyle;
      }
      let editableStyle = hasEditableConfig ? "Inline" : "Container";
      if (props.tableCommonAttr.editConfig && props.tableCommonAttr.editConfig.hasOwnProperty("editableStyle")) {
        editableStyle = props.tableCommonAttr.editConfig.editableStyle;
      }
      const triggerConfig = { trigger: "manual", mode: "row" };
      if (editableStyle === "Inline") {
        triggerConfig.trigger = "click"; //"Manual"//
        triggerConfig.mode = "row";
        triggerConfig.enabled = true;
        triggerConfig.showUpdateStatus = true;
        triggerConfig.showInsertStatus = true;
      }
      return { editableStyle, submitStyle, ...triggerConfig,vmTemplateConfig: crudServiceVmTemplateConfig.table };
      //return editConfig
    } else {
      return {};
    }
  });
  /* 
    
    
    */
};

/**
 */
export const useComputedRowConfig = (props) => {
  return computed(() => {
    return {
      keyField: props.tableCommonAttr?.rowConfig?.keyField ?? props.tableCommonAttr?.treeTableConfig?.KeyField ?? "id",
      parentKeyField:
        props.tableCommonAttr?.rowConfig?.parentKeyField ??
        props.tableCommonAttr?.treeTableConfig?.parentKeyField ??
        "parentId",
      isCurrent: true,
      isHover: true,
    };
  });
};

/**
 * 表格列配置
 */
export const useComputedColumnConfig = (props) => {
  return computed(() => {
    return {
      resizable: true,
      //width: "auto",
      minWidth: "100px",
    };
  });
};

/**
 * 树表箭头是否在当前列显示
 */
export const isTreeNode = (tableCommonAttr, fieldKey) => {
  const treeNodeKeys = tableCommonAttr?.treeTableConfig?.treeNodeKeys ?? ["buildInSeq"];
  return treeNodeKeys.includes(fieldKey);
};

export const getBuildInColumnType = (tableCommonAttr, fieldKey) => {
  const obj = tableCommonAttr?.buildInColumnConfig ?? {};
  const typeMappings = {
    buildInSeq: "seq",
    buildInCheckbox: "checkbox",
    buildInExpand: "expand",
  };
  const matchedTypeKey = Object.keys(obj).find((typeKey) => {
    return obj[typeKey]?.config?.labelField === fieldKey;
  });
  if (matchedTypeKey) {
    return typeMappings[matchedTypeKey];
  } else {
    return undefined;
  }
};
